package com.servlet;

import com.dao.UserDao;
import com.dao.impl.UserDaoImpl;
import com.entry.User;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/system/pass.do")
public class UppassServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session = req.getSession();
        JsonParser jParser = new JsonParser();
        JsonObject jt = (JsonObject) jParser.parse(req.getParameter("c"));//构造JsonObject对象
        String pass = jt.get("pass").getAsString();
        String pass1 = jt.get("pass1").getAsString();
        User user = (User) session.getAttribute("user");
        UserDao userDao = new UserDaoImpl();
        if(pass.equals(pass1)){
            session.setAttribute("supueMess","密码不一致");
            String mess = validateForm(pass);
            if(!"".equals(mess)){
                session.setAttribute("supueMess",mess);
            }else{
                if(userDao.update(pass,user.getUsername()) != 0){
                    session.setAttribute("supueMess","修改成功");
                }else{
                    session.setAttribute("supueMess","修改失败");
                }
            }
        }
        resp.sendRedirect("./uppass.jsp");
    }
    private  String validateForm(String pass){
        if(pass == null || !pass.matches("\\w{6,20}")){
            return "*密码名不合法！";
        }
        return "";
    }
}
